﻿#ifndef TCPCLIENTDEMOD_H
#define TCPCLIENTDEMOD_H

#include <QHostAddress>
#include <QObject>
#include <QTimerEvent>

#include <net/listener.h>
#include <net/netreading.h>

using namespace QtSocket;
namespace QtSocket{
class TcpClient;
class NetWriting;
}

/**
 * @brief The TcpClientTest class 表示tcpClient的类测试。
 */
class TcpClientDemo
        : public QObject,
        public NetReading,
        public ISessionListener
{
    Q_OBJECT
public:
    explicit TcpClientDemo(QObject *parent = nullptr);
    ~TcpClientDemo() override;
    /**
     * @brief bind 绑定本机Tcp地址。
     * @param localAddress
     * @param localPort
     * @return
     */
    bool bind(QHostAddress localAddress, quint16 localPort);
    /**
     * @brief setAutoConnect  设置自动连接。
     * @param isAuto
     */
    void setAutoConnect(bool isAuto);
    /**
     * @brief connect 连接服务端。
     * @param remoteAddres
     * @param remotePort
     */
    void connect(QHostAddress remoteAddress, quint16 remotePort);
    /**
     * @brief stop 停止方法。
     */
    void stop();
signals:
    void log_signal(QString logInfo);
    // TcpReading interface
public:
    void onProc(const QByteArray &arry) override;
    // QObject interface
protected:
    void timerEvent(QTimerEvent *event) override;

    // ISessionListener interface
public:
    void onStateChanged(QtSocket::TcpSession *session, bool connected) override;
    void onError(QAbstractSocket::SocketError error) override;

public slots:
    /**
     * @brief fulfil  写入完毕回调。
     */
    void fulfil(QSharedPointer<QtSocket::NetWriting> sender, int size);
private:
signals:
    void stop_signal();
private slots:
    void stop_slot();
private:
    QtSocket::TcpClient *m_client;
    QtSocket::TcpSession *m_session;  //  保存当前会话实例。
    QHostAddress m_localAddress;
    quint16 m_localPort;
    int m_timerID;
    QAtomicInt m_counter; // 数据发送计数器。
    bool m_isAutoConnect; // 是否自动连接。
    bool m_stopped; // 是否关闭。

};

#endif // TCPCLIENTDEMOD_H
